package com.broada.apm.logic;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;

import com.broada.apm.ApmServer;
import com.broada.apm.base.BaseLogic;
import com.broada.apm.es.indices.support.PerfIndicesBuilder;
import com.broada.apm.indicator.api.ApmClientFactory;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.model.Service;
import com.broada.apm.utils.ConfigureProperties;

public class ClearDisServicePerf extends BaseLogic {
	
	private PerfIndicesBuilder builder = PerfIndicesBuilder.getInstance();
	private String perf_keep_hour = ConfigureProperties.getString("disservice.perf.keep.hour", "1");
	
	public void clear() throws ApmDataIndicatorException {
		String[] delIndex = null;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - Integer.valueOf(perf_keep_hour));
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		
		// 查询所有交易索引
		String[] indexs = builder.searchIndex(String.format("apm_perf_a%s_*_m%s", ApmServer.APP_DEFAULT_ID, calendar.get(Calendar.MONTH)+1));
		if(indexs != null && indexs.length > 0){
			for (String index : indexs) {
				if(index.indexOf("k") < 0) {
					delIndex = (String[]) ArrayUtils.add(delIndex, index);
				}
			}
			if (ArrayUtils.isNotEmpty(delIndex)) {
				perService.clearDisServicePerf(delIndex, builder.TYPE, calendar.getTimeInMillis(), getFocusDisService());
			}
		}
	}
	
	public String[] getFocusDisService() {
		String[] serviceIds = null;
		Service service = new Service();
		service.setFocus(1);
		List<Service> services = ApmClientFactory.getApmClient().getServiceService().getDisServiceFocusOrNot(service, null, "id", true, 0, Integer.MAX_VALUE, 0, new Date(), new Date());
		if (!services.isEmpty()) {
			serviceIds = new String[services.size()];
			for (int i=0; i<services.size(); i++) {
				serviceIds[i] = services.get(i).getId();
			}
		}
		return serviceIds;
	}
}
